/*
 *  HeartBeatController.cpp
 *  project8
 *
 *  Created by Luca Gobbo on 21-06-10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include "HeartBeatController.h"
#include "string.h"
          
                            
HeartBeatController::HeartBeatController(InfraredSensor * sensor)
: cTask("HeartBeatControlTask",3), theInfraredSensor(sensor) , hbFlags(3), theLed(1)
{ }

void HeartBeatController::run(){
  state = RUN;
  timer2.set(5 MS, this);
}

void HeartBeatController::disable(){
  state = STB;
  timer2.cancel();
}

int HeartBeatController::getHbCur(){
  return (int)hbCUR;
}

int HeartBeatController::getHbAvg(){
  return (int)hbAVG;
}
int HeartBeatController::getHbLow(){
  return (int)hbLOW;
}

int HeartBeatController::getHbHigh(){
  return (int)hbHIGH;
}

void HeartBeatController::init(void){
    
    tzMAX = 180;
    tzMIN = 150;
    
    first = 1;
    hbCUR = 0;
    hbHIGH = 0;
    hbLOW = 0;
    time = 0;
    beats = 0;
    prevTime = 0;
    theInfraredSensor->setListener(this);
    theLed.off();
    state = STB;
    hbFlags.wait();

}

void HeartBeatController::timeout(Timer* src){
  if (src == &timer){
    hbFlags.set(ledFlagNo);
    }
  if (src == &timer2){  
    hbFlags.set(timerFlagNo);
  }
}

void HeartBeatController::update(void){ 
  switch(hbFlags.getFlagNo()){
    case hbFlagNo:
      if (state == RUN){
        beats++; 
        timer.set(100 MS,this);
        theLed.on();
        prevLedTime = time;
        hbCUR = 60.0 / ((time-prevTime) * 0.005);
        hbAVG = (beats / (time * 0.005)) *60.0; 
        
        if (hbLOW == 0 || hbLOW > hbCUR ) hbLOW = hbCUR;  
        if (first) first = 0;
        else if (hbHIGH < hbCUR ) hbHIGH = hbCUR;      
       
        if (hbCUR > tzMAX) {  
          theSpeakerSwitch.switchOn(500, 50 MS);
        }
        if (hbCUR < tzMIN){
          theSpeakerSwitch.switchOn(250, 100 MS);
        }
        prevTime = time;
      }
    break;
    
  case ledFlagNo:
    if (state == RUN){
      theLed.off();
      }
    break;  
  case timerFlagNo:
    if (state == RUN){
      time++;
      timer2.set(5 MS, this);
  //if (time > prevLedTime + 5)
    }
    
    break; 
     
  }
  hbFlags.wait();
}


void HeartBeatController::heartBeat(void){
    hbFlags.set(hbFlagNo);
}



